package com.zengqingfa.springboot.redis.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.zengqingfa.springboot.redis.entity.ComRegionInfo;
import com.zengqingfa.springboot.redis.mapper.ComRegionInfoMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;


/**
 * @Author: slfx
 * @Date: 2022-10-28
 * @Description:
 **/
@RestController
@RequestMapping("/comRegionInfo")
public class ComRegionInfoController {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ComRegionInfoMapper comRegionInfoMapper;


    @GetMapping("/getRegionsByParentCode")
    public List<ComRegionInfo> getRegionsByParentCode(String parentCode) {
        String cacheKey = "REGION:" + parentCode;
        //获取值 start:0 end:-1 表示获取所有的元素
        List<ComRegionInfo> comRegionInfos = redisTemplate.opsForList().range(cacheKey, 0, -1);
        if (CollectionUtil.isEmpty(comRegionInfos)) {
            //从数据库获取
            comRegionInfos = comRegionInfoMapper.selectList(new LambdaQueryWrapper<ComRegionInfo>().eq(ComRegionInfo::getPregionCode, parentCode));
            //设值到redis中
            if (CollectionUtil.isEmpty(comRegionInfos)) {
                return Lists.newArrayList();
            }
            //设置值
            redisTemplate.opsForList().leftPushAll(cacheKey, comRegionInfos);
        }
        return comRegionInfos;
    }

    @GetMapping("/deleteRegionsByParentCode")
    public Boolean deleteRegionsByParentCode(String parentCode) {
        String cacheKey = "REGION:" + parentCode;
        //删除对应的key
        Boolean delete = redisTemplate.delete(cacheKey);
        return delete;
    }
}
